package com.it.iostream.Service.Impl;

import java.io.*;
import java.util.HashMap;

import com.it.iostream.Dao.FileDao;
import com.it.iostream.Dao.ResPonseResult;
import com.it.iostream.Mapper.FileMapper;
import com.it.iostream.Utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;

//Utils类
import static com.it.iostream.Utils.Suffix.getSuffix;
import static com.it.iostream.Utils.MD5Utils.getSaltMD5;
import static com.it.iostream.Utils.ResPonseResultUtils.ResResult;

@Service
public class FileServiceImpl extends BaseService implements com.it.iostream.Service.FileService {

    @Resource
    private FileMapper fileMapper;

    @Resource
    private IdWorker idWorker;

    public static String path;

    @Value("${upload.path}")
    public void setPath(String path) {
        FileServiceImpl.path = path;
    }


/*
* 上传文件
* */
    public ResPonseResult uploadfile(@NotNull @NotEmpty MultipartFile file)throws Exception {
             //雪花id
             String idwork = String.valueOf(idWorker.nextId());
             //获取文件的原文件名称-> 文件名称+文件拓展名 更改为雪花id外加后缀名
            //filename 客户下载的文件
            String filenameOriginal = file.getOriginalFilename();
            String filename = idwork + getSuffix (file.getOriginalFilename());
             //获取文件的类型
             String type =getSuffix (filenameOriginal);
             //获取文件大小
             int filesize = (int) file.getSize();
             //获取当前的上传时间->精确到秒
             SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
             Date createtime = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
             //进行md5加密
             String md5 = getSaltMD5(type + filenameOriginal + filesize + path);
             //解密 getSaltverifyMD5(type+filename+filesize,加密后的密码)
             //写入文件   名字为：文件的本身名字+当前时间
             String nowtime = new SimpleDateFormat("yyyyMMdd").format(new Date());
             FileUtils.writefile(file.getInputStream(),path,filename,nowtime);

             //写入数据库
             FileDao fileDao = new FileDao();
             fileDao.setSeq(idwork);    fileDao.setFilename(filenameOriginal);
             fileDao.setType(type);     fileDao.setFileSize(filesize);
             fileDao.setCreateTime(createtime);    fileDao.setMd5(md5);
             //创建的文件夹是Image还是File
             String readsomething = ReadProperties.readsomething(filenameOriginal);
     fileDao.setPath(path+File.separator+nowtime+File.separator+readsomething+File.separator+filename);
             fileMapper.insert(fileDao);

             //返回
        HashMap<String,String> hm = new HashMap<>();
        hm.put("fileseq",idwork);
    return  ResResult(200,"成功",hm);

    }

/*
*  上传图片
* */
    @Override
    public ResPonseResult ImgUpload(MultipartFile file) throws Exception {
        return uploadfile(file);
    }

/*
* 通过seq拿取图片或者文件
* */
    @Override
    public  byte[] findbyseq(String seq,HttpServletResponse response) throws Exception {
        //拿到前端传入的seq
        FileDao fileDao = fileMapper.selectById(seq);
        //拿到数据库路径源文件
        String path = fileDao.getPath();
        String name = fileDao.getFilename();
        File file = new File(path);
        byte[] bytes = null;
        //是文件还是图片，图片展示，文件下载
        if(path.contains("Image")){
            FileInputStream inputStream = new FileInputStream(file);
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
        }else{
            FileUtils.downloadFile(path,name,response);
        }
        return bytes;
    }


}
